/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cw.jeeyt.common.web;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.cw.jeeyt.common.utils.CaptchaMaker;

/**
 * 控制器支持类
 *
 * @author ThinkGem
 * @version 2013-3-23
 */
public abstract class BaseController {

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 返回验证码
     */
    public void makeCaptcha(HttpServletResponse response) {
        CaptchaMaker.init(response)
            .start();
    }

    /**
     * 添加Model消息
     *
     * @param messages
     */
    protected void addMessage(Model model, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message)
                .append(messages.length > 1 ? "<br/>" : "");
        }
        model.addAttribute("message", sb.toString());
    }

    /**
     * 添加Flash消息
     *
     * @param messages
     */
    protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message)
                .append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("message", sb.toString());
    }

    /**
     * 客户端返回JSON字符串
     *
     * @param response
     * @param object
     * @return
     */
    protected void renderString(HttpServletResponse response, Object object) {
        renderString(response, JSON.toJSONString(object), "application/json");
    }

    /**
     * 客户端返回JSON字符串
     *
     * @param response
     * @param object
     * @return
     */
    protected void renderListString(HttpServletResponse response, Object object) {
        try {
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html; charset=utf-8");
            response.getWriter()
                .print(object);
        } catch (IOException e) {
            logger.error("返回数据到客户端出错：" + e.getMessage());
        }
    }

    /**
     * 客户端返回字符串
     *
     * @param response
     * @param string
     * @return
     */
    protected void renderString(HttpServletResponse response, String string, String type) {
        try {
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html; charset=utf-8");
            response.getWriter()
                .print(string);
        } catch (IOException e) {
            logger.error("返回数据到客户端出错：" + e.getMessage());
        }
    }
}
